package com.zhengjiang.sms.consumer.listener;

import com.google.gson.Gson;
import com.zhengjiang.sms.common.Const;
import com.zhengjiang.sms.consumer.model.LoginDto;
import com.zhengjiang.sms.consumer.model.SmsDto;
import com.zhengjiang.sms.consumer.service.ISendSmsService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName consumer
 * @Description
 * @Author zhengjiang(99514925 @ qq.com)
 * @Date 2020-06-02 15:22
 * @Version V1.0
 **/
@Component
@RabbitListener(queues = Const.SMS_DIRECT_QUEUE)
public class SmsConsumer {

    @Autowired
    ISendSmsService sendSmsService;
    @Autowired
    RedisTemplate redisTemplate;

    @RabbitHandler
    public void process(String message) {
        System.out.println(message);
        Gson gson = new Gson();
        LoginDto loginDto = gson.fromJson(message, LoginDto.class);
        //调用阿里云短信服务发送短信
        SmsDto smsDto = new SmsDto();
        smsDto.setPhoneNumbers(loginDto.getPhone());
        Map<String,String> codeParams = new HashMap<String, String>();
        codeParams.put("code",loginDto.getCode());
        smsDto.setTemplateParam(gson.toJson(codeParams));
        sendSmsService.sendSms(smsDto);
        //手机号和验证码缓存到redis中60s
        redisTemplate.opsForValue().set(loginDto.getPhone(),loginDto.getCode(),60, TimeUnit.SECONDS);
    }

}
